package com.xinchuang.service.impl;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:报价导出时记录变量位置
 * @Author: thh
 * @Date: 2023/10/13 13:59
 */
@Slf4j
@Data
@Component
public class ExportOutQuotationReadListener extends AnalysisEventListener<Map<Integer, String>> {

    /**
     * 模板数据变量信息list
     */
    private List<Map<String, String>> templateDataList = new ArrayList<>();
    /**
     * 模板数据变量信息map
     */
    public Map<String, List<Integer>> templateDataMap = new LinkedHashMap<>();


    @Override
    public void invoke(Map<Integer, String> rowData, AnalysisContext context) {
        ReadRowHolder rowHolder = context.readRowHolder();
        // 行索引
        int rowIndex = rowHolder.getRowIndex();
        for (Map.Entry<Integer, String> entry : rowData.entrySet()) {
            // 列索引
            Integer columnIndex = entry.getKey();
            // 单元格数据
            String cellData = entry.getValue();
            if (cellData != null && cellData.startsWith("{") && cellData.endsWith("}")) {
                Map<String, String> templateDataMap = new HashMap<>();
                templateDataMap.put("index", rowIndex + "-" + columnIndex);
                templateDataMap.put("value", cellData);
                templateDataList.add(templateDataMap);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 解析完成后的操作
        Map<String, List<String>> dataMap = templateDataList.stream()
                .collect(Collectors.groupingBy(map -> map.get("value"), LinkedHashMap::new, Collectors.toList()))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue().size() > 1)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .map(item -> item.values().iterator().next())
                                .collect(Collectors.toList()),
                        (oldValue, newValue) -> newValue, LinkedHashMap::new
                ));

        templateDataMap = dataMap.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> {
                            List<String> values = entry.getValue();
                            int rowStartIndex = Integer.valueOf(values.get(0).split("-")[0]);
                            int rowEndIndex = Integer.valueOf(values.get(0).split("-")[0]);
                            int columnStartIndex = Integer.valueOf(values.get(0).split("-")[1]);
                            int columnEndIndex = Integer.valueOf(values.get(0).split("-")[1]);
                            for (String index : values) {
                                int rowIndex = Integer.valueOf(index.split("-")[0]);
                                int columnIndex = Integer.valueOf(index.split("-")[1]);
                                rowStartIndex = Math.min(rowStartIndex, rowIndex);
                                rowEndIndex = Math.max(rowEndIndex, rowIndex);
                                columnStartIndex = Math.min(columnStartIndex, columnIndex);
                                columnEndIndex = Math.max(columnEndIndex, columnIndex);
                            }
                            return Arrays.asList(rowStartIndex, rowEndIndex, columnStartIndex, columnEndIndex);
                        }, (oldValue, newValue) -> newValue, LinkedHashMap::new));

        log.debug("模板变量位置信息:{}", JSON.toJSONString(templateDataMap));
    }

}
